package com.haimi.shiguang.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;

import com.haimi.shiguang.base.AppCache;
import com.haimi.shiguang.framework.GlobalCache;


/**
 * Comments: 连续点击返回按钮时（2秒之内），退出应用的辅助类
 */
public class AppExitHelper {
    private static final int DELAY_MILLIS = 2000;

    private Context mContext;

    private Handler mHandler;


    private boolean isKeyDownHandling = false;

    private Runnable timeJob = new Runnable() {
        @Override
        public void run() {
            isKeyDownHandling = false;
        }
    };

    public AppExitHelper(Context ctx) {
        this.mContext = ctx;
        this.mHandler = new Handler(Looper.getMainLooper());
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode != KeyEvent.KEYCODE_BACK) {
            return false;
        }
        if (isKeyDownHandling) {
            mHandler.removeCallbacks(timeJob);
            AppCache.getInstance().appExit(GlobalCache.getContext());
        } else {
            isKeyDownHandling = true;
            ToastUtil.showToast("再次点击退出应用");
            mHandler.postDelayed(timeJob, DELAY_MILLIS);
        }

        return true;
    }
}
